package com.hzw.saas.web.sso.security;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import com.hzw.saas.web.sso.pojo.model.SaasClient;
import com.hzw.saas.web.sso.service.ISaasClientService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author sonam
 * @sine 2021/10/29 2:04 下午
 */
@Service
@RequiredArgsConstructor
public class ClientDetailsServiceImpl implements ClientDetailsService {

    private final ISaasClientService clientService;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        SaasClient saasClient = clientService.getById(clientId);

        BaseClientDetails clientDetails = null;
        if(Objects.nonNull(saasClient)) {
            clientDetails = new BaseClientDetails();
            clientDetails.setClientId(saasClient.getId());
            clientDetails.setAutoApproveScopes(Collections.singletonList("true"));
            clientDetails.setClientSecret(saasClient.getClientSecret());
            clientDetails.setScope(Arrays.stream(saasClient.getScope().split(StrUtil.COMMA)).collect(Collectors.toList()));
            clientDetails.setResourceIds(Arrays.stream(saasClient.getResourceIds().split(StrUtil.COMMA)).collect(Collectors.toList()));
            clientDetails.setAuthorizedGrantTypes(Arrays.stream(saasClient.getAuthorizedGrantTypes().split(StrUtil.COMMA)).collect(Collectors.toList()));
            clientDetails.setRegisteredRedirectUri(Arrays.stream(saasClient.getRedirectUri().split(StrUtil.COMMA)).collect(Collectors.toSet()));
            clientDetails.setAuthorities(new ArrayList<>());
            clientDetails.setAccessTokenValiditySeconds(saasClient.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(saasClient.getRefreshTokenValidity());
            clientDetails.setAdditionalInformation(Maps.newHashMap());
        }
        return clientDetails;
    }

}
